# 创建标准属性
from time import sleep

import pandas as pd
from base.base import Base
import json

from dao.mysqlhelper import MySQLHelper
from utils.config import Config


def get_token():
    url=f'http://{base_url}/idaas/idaas-gateway/wutong-idaas-auth/login'
    headers={
        'content-type':'application/json',
        'tenantid':'defaultTenantId'
    }
    data={
        "password": "ff960e9eeeff3b417fbf44bdc8f8d8c1",
        "username": "zzh",
        "captchaCode": "11",
        "captchaKey": "d1a780db-cdce-4900-886d-dbbbb68f743b"
    }
    res=json.loads(base.send_post(url,param_type,headers=headers,data=data))
    return res['data']['Authorization']

# 读取Excel文件，文件里的值最好都设置成文本
file_path = 'D:\\IOT3.0\\2024.09\\实体赋码平台\\标准分类&属性&模型导信息_1026.xlsx'  # 替换为你的文件路径
df = pd.read_excel(file_path, engine='openpyxl',sheet_name='标准属性', skiprows=1)
config=Config('../conf/config.ini')

mysql=MySQLHelper()
sql='select config_name from entity_attribute_dict where del_flag=0'
res=mysql.select(sql)
name_list=[item[0] for item in res]
base_url=config.read_value('system','base_url')

# 遍历每一行数据
for index, row in df.iterrows():
    base=Base()
    url=f'http://{base_url}/gateway/code-one/entityAttributeDict/save'
    param_type='application/json'
    headers={
        'content-type':'application/json',
        'authorization':get_token()
    }
    #检查属性名称是否有重复
    if row['属性名称'] in name_list:
        print(f"{row['属性名称']}  属性已存在，建议更换")
        continue

    # 检查数据类型是否为 NaN，并处理默认值
    data_type = str(row['数据类型']) if pd.notna(row['数据类型']) else '未知类型'

    # 获取配置范围，如果为 NaN，则设为 ''
    config_scope = row['配置范围'] if pd.notna(row['配置范围']) else ''
    try:
        if row['数据类型']=='实体统一码':
            data={
                "configName": row['属性名称'],
                "configKey": row['属性code'],
                "dataType": config.read_value('attribute','实体统一码'),
                "status": 0,
                "attributeType": "0"
            }
        elif row['数据类型']=='数值':
            data={
                "configName": row['属性名称'],
                "configKey": row['属性code'],
                "dataType": config.read_value('attribute','数值'),
                "configUnit": "kg",
                "status": 0,
                "configScope": config_scope,
                "attributeType": "0"
            }
        else:
            data={
                "configName": row['属性名称'],
                "configKey": row['属性code'],
                "dataType": config.read_value('attribute',str(row['数据类型'])),
                "status": 0,
                "configScope": config_scope,
                "attributeType": "0"
            }
        res=json.loads(base.send_post(url,param_type,headers=headers,data=data))
        sleep(2)
        # 检查请求是否成功
        if res['msg'] == '新增成功':
            print(f"成功提交第 {index + 1} 行数据: {data}")
        else:
            print(f"第 {index + 1} 行数据提交失败，状态码: {res.status_code}, 响应: {res.text}")
    except KeyError as e:
        print(f"配置文件中缺少选项: {e}")

    except Exception as ex:
        print(f"处理行 {index} 时发生错误: {ex}")

